/**    
 * @{#} BuweiActivity.java Create on 2014-6-9 下午8:50:36    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.FlowLayout;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.OTab;
import cn.o.app.ui.OTabItem;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.connection.remotefile.RemoteImageDownloader;
import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.evan.common.share.ShareCallBack;
import com.evan.common.share.ShareQQUtils;
import com.evan.common.share.ShareWXUtils;
import com.evan.common.utils.FilesUtil;
import com.evan.common.utils.ImageUtils;
import com.pifuke.adapter.TreatmentProjectListAdapter;
import com.smiier.skin.adapter.QuestionAdapter;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.TreatmentProjectItemExtra;
import com.smiier.skin.extra.UserExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.DoctorTreatmentProjectListTask;
import com.smiier.skin.net.DoctorTreatmentProjectListTask.DoctorTreatmentProjectItem;
import com.smiier.skin.net.DoctorTreatmentProjectListTask.DoctorTreatmentProjectListRequest;
import com.smiier.skin.net.DoctorTreatmentProjectListTask.DoctorTreatmentProjectListResponse;
import com.smiier.skin.net.QuestionLimitCheckTask;
import com.smiier.skin.net.QuestionLimitCheckTask.QuestionLimitCheckRequest;
import com.smiier.skin.net.QuestionLimitCheckTask.QuestionLimitCheckResponse;
import com.smiier.skin.net.SysShareCallBackTask;
import com.smiier.skin.net.SysShareCallBackTask.SysShareCallBackRequest;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.ui.QuestionFragment;
import com.smiier.skin.ui.QuestionFragment.ContactActionItem;
import com.smiier.skin.ui.QuestionLimitDialog;
import com.smiier.skin.ui.QuestionLimitDialog.QuestionLimitDialogListener;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.util.ShareUtil;
import com.smiier.skin.utils.CommonUtility;

@SuppressLint("InflateParams")
@SuppressWarnings("deprecation")
public class DoctorDetailActivity extends BasicActivity implements
		OnRefreshListener<ListView>, OnItemClickListener {

	private PullToRefreshListView list_question_detail;

	private OImageView img_doctor_icon;
	QuestionAdapter adapter;

	HashMap<String, Object> params = new HashMap<String, Object>();
	int start_qid;
	ArrayList<Object> array = new ArrayList<Object>();
	JSONObject doctor, doctorInfo;
	String qid;
	TextView mTextEmpty;
	TextView text_doctor_name, text_hospital_name, text_doctor_title,
			text_answer_num, text_haoping_num, text_guanzhu_num;
	FlowLayout text_skill;
	Button btn_charge_to_zixun, btn_charge_to_zixun_by_invite;
	TextView btn_guanzhu;
	protected boolean mSmsCatching = false;
	TextView mLevel;
	TextView mDesc;
	User mUser;
	OTab mTab;
	OTabItem mRecoder, mTreatment;
	boolean mLoadTreatment = false;
	TreatmentProjectListAdapter mAdapter;
	LinearLayout mParent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_doctor_detail);

		list_question_detail = (PullToRefreshListView) findViewById(R.id.list_question_detail);

		init();

		final View headView = LayoutInflater.from(activity).inflate(
				R.layout.view_doctor_detail_head, null);
		mTextEmpty = (TextView) headView.findViewById(R.id.empty);
		mParent = (LinearLayout) headView.findViewById(R.id.empty_parent);
		mTab = (OTab) headView.findViewById(R.id.tab);
		mRecoder = (OTabItem) headView.findViewById(R.id.recoder);
		mTreatment = (OTabItem) headView.findViewById(R.id.treatments);
		setNavRightBtnDrawable(R.drawable.btn_share);
		mTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public void onChanged(View v, int index) {

				if (index == 0) {
					mLoadTreatment = false;
					list_question_detail.setAdapter(adapter);
				} else if (index == 1) {
					mLoadTreatment = true;
					list_question_detail.setAdapter(mAdapter);
				}
				list_question_detail.pullHeaderLayout(OUtil.dp2px(getContext(),
						60));
				list_question_detail.doPullRefreshing(true);
				setContextEmptyType(false, 2);

			}
		});
		list_question_detail = (PullToRefreshListView) findViewById(R.id.list_question_detail);
		list_question_detail.setOnRefreshListener(this);
		mLevel = (TextView) headView
				.findViewById(R.id.treatment_hospital_level);
		list_question_detail.setPullLoadEnabled(false);
		list_question_detail.setPullRefreshEnabled(false);
		list_question_detail.setScrollLoadEnabled(true);
		mDesc = (TextView) findViewById(R.id.text_doctor_desc);
		text_doctor_name = (TextView) headView
				.findViewById(R.id.text_doctor_name);
		text_hospital_name = (TextView) headView
				.findViewById(R.id.text_hospital_name);
		text_hospital_name.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(DoctorDetailActivity.this,
						HospitalActivity.class);
				UserExtra extra = new UserExtra();
				extra.setUser(mUser);
				if (extra.putTo(i)) {
					startActivity(i);
				}
			}
		});
		text_doctor_title = (TextView) headView
				.findViewById(R.id.text_doctor_title);
		text_skill = (FlowLayout) headView.findViewById(R.id.text_skill);

		text_answer_num = (TextView) headView
				.findViewById(R.id.text_answer_num);
		text_haoping_num = (TextView) headView
				.findViewById(R.id.text_haoping_num);
		text_guanzhu_num = (TextView) headView
				.findViewById(R.id.text_guanzhu_num);
		img_doctor_icon = (OImageView) headView
				.findViewById(R.id.img_doctor_icon);
		btn_guanzhu = (TextView) headView.findViewById(R.id.btn_guanzhu);
		btn_charge_to_zixun = (Button) headView
				.findViewById(R.id.btn_charge_to_zixun);
		btn_charge_to_zixun_by_invite = (Button) headView
				.findViewById(R.id.btn_charge_to_zixun_by_invite);
		TextView img_cert = (TextView) headView.findViewById(R.id.img_cert);
		LinearLayout llHeadProfile = (LinearLayout) headView
				.findViewById(R.id.ll_head_profile);
		mAdapter = new TreatmentProjectListAdapter();
		try {
			doctor = new JSONObject(getIntent().getStringExtra(
					Constant.IDENTITY_KEY));
			params.put(Constant.PARAM_API, "Question.GetList");
			params.put("pageSize", Constant.pageSize);
			params.put("statuses", 3);
			params.put("doctor_uid", doctor.getString("Uid"));
			if (doctor.has("User")) {
				doctorInfo = doctor.getJSONObject("User");
			} else {
				doctorInfo = doctor;
			}
			mUser = JsonUtil.convertFromObject(doctorInfo, User.class);
			int is_cert = mUser.Is_Cert;
			if (is_cert == 1) {
				img_cert.setVisibility(View.VISIBLE);
			}
			setNavTitle(mUser.Name);
			double zixunCost = mUser.Cost;
			if (zixunCost > 0) {
				String charge = zixunCost + "";
				if (charge.endsWith(".0")) {
					charge = charge.substring(0, charge.length() - 2);
				}
				btn_charge_to_zixun.setText("图文咨询 ￥" + charge);
			} else {
				btn_charge_to_zixun.setText("图文咨询");
			}
			text_doctor_name.setText(mUser.Name);
			String hospital = mUser.Hospital;

			StringBuilder sb = new StringBuilder();
			for (String tmp : mUser.Professional) {
				sb.append(tmp).append(",");
			}
			text_doctor_title.setText(sb.toString().subSequence(0,
					sb.toString().length() - 1));
			text_hospital_name.setText(hospital);

			CommonUtility.setHosLevel(mUser.Hospital, mLevel);
			if (!CommonUtility.isNull(mUser.Desc)) {
				mDesc.setText("简介：" + mUser.Desc);
				mDesc.setVisibility(View.VISIBLE);
			}
			// text_skill.setText(CommonUtility.convertJSONArray2String(
			// doctorInfo.getJSONArray("Skilled"), "、"));

			for (String str : mUser.Skilled) {
				if (str != null && !str.trim().equals("")) {
					CheckBox button = (CheckBox) LayoutInflater.from(
							getContext()).inflate(R.layout.item_filter_button,
							null);
					button.setEnabled(false);
					button.setClickable(false);
					button.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

						}
					});
					button.setText(str);

					text_skill.addView(button);

				}
			}

			String iconPath = mUser.Pic;
			if (iconPath.indexOf(".") == -1) {
				iconPath = iconPath + Constant.IMG_TH;
			}
			// mBitmapUtils.display(img_doctor_icon,
			// GlobalSettings.SERVER_IMG_URL
			// + iconPath, new OBitmapLoadCallBack<View>());
			CommonUtility.displayHeadImage(img_doctor_icon, mBitmapUtils,
					GlobalSettings.SERVER_IMG_URL + iconPath, getResources(),
					mUser.Sex);
			String name = RemoteImageDownloader.getFileNameString(iconPath,
					false);
			Bitmap bitmap = CommonUtility.getBitmapCache(name);
			if (CommonUtility.isNull(bitmap)) {
				String path = FilesUtil.getRootPath() + name;
				bitmap = BitmapFactory.decodeFile(path,
						ImageUtils.getOptionsTh(path));
			}
			// Bitmap blurBitmap = ImageUtils.blurBitmap(bitmap, 15);
			// BitmapDrawable bd = new BitmapDrawable(getResources(),
			// blurBitmap);
			// llHeadProfile.setBackgroundDrawable(bd);

			if (!CommonUtility.isNull(GlobalSettings.sUser)) {
				try {
					RequestTaskIntercept.requestIntercept(activity,
							Constant.URL.REQUEST, new RequestHandler(activity,
									new HandlerCallback() {

										@Override
										public void callback(Object o) {
											if (!CommonUtility.isNull(o)) {
												JSONObject object = (JSONObject) o;
												if (CommonUtility
														.response200(object)) {
													try {
														JSONArray array = object
																.getJSONArray(Constant.JSON_PARAM_RES);
														if (array.length() > 0) {
															btn_guanzhu
																	.setText("取消关注");
														} else {
															btn_guanzhu
																	.setBackgroundResource(R.drawable.round_btn_green);
															btn_guanzhu
																	.setText("关注");
														}
													} catch (Exception e) {
														e.printStackTrace();
													}
												}
											}
										}
									}), false, CommonUtility.params(
									new String[] { Constant.PARAM_API, "uids",
											Constant.PARAM_TOKEN },
									new String[] { "Follow.Check",
											doctorInfo.getString("Uid"),
											GlobalSettings.sToken }));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			btn_guanzhu.setVisibility(View.VISIBLE);

			// 如果当前用户角色是医生，则不显示医生的咨询按钮
			if (CommonUtility.isDoctor()) {
				btn_charge_to_zixun.setVisibility(View.GONE);
			}

			if (GlobalSettings.sUid == doctorInfo.getInt("Uid")) {
				btn_guanzhu.setVisibility(View.GONE);
			}

			if (doctorInfo.getInt("Is_Accept_Invite") == 1
					&& !CommonUtility.isDoctor()) {
				btn_charge_to_zixun_by_invite.setVisibility(View.VISIBLE);
			}

			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST, new RequestHandler(activity,
							new HandlerCallback() {

								@Override
								public void callback(Object o) {
									if (!CommonUtility.isNull(o)) {
										JSONObject object = (JSONObject) o;
										try {
											JSONArray array = object
													.getJSONArray(Constant.JSON_PARAM_RES);
											for (int i = 0; i < array.length(); i++) {
												JSONObject oo = array
														.getJSONObject(i);
												int key = oo.getInt("Key");
												if (key == 2010) {
													JSONObject value = oo
															.getJSONArray(
																	"Value")
															.getJSONObject(0);
													text_answer_num.setText(value
															.getString("Value"));
												}
												if (key == 2002) {
													JSONObject value = oo
															.getJSONArray(
																	"Value")
															.getJSONObject(0);
													text_haoping_num.setText(value
															.getString("Value"));
												}
												if (key == 2005) {
													JSONObject value = oo
															.getJSONArray(
																	"Value")
															.getJSONObject(0);
													text_guanzhu_num.setText(value
															.getString("Value"));
												}
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}), false, CommonUtility.params(new String[] {
							Constant.PARAM_API, "types", "uids" },
							new String[] { "Counter.Get", "2010,2002,2005",
									doctorInfo.getString("Uid") }));

		} catch (Exception e) {
			e.printStackTrace();
		}

		// list_question_detail.doPullRefreshing(true);
		adapter = new QuestionAdapter(activity, array);
		list_question_detail.getListView().addHeaderView(headView);
		list_question_detail.setAdapter(adapter);
		list_question_detail.doPullRefreshing(true);
		list_question_detail.setOnItemClickListener(this);
		registerReceiver();

		// 监听短信
		this.getContentResolver().registerContentObserver(
				Uri.parse("content://sms/"), true,
				new ContentObserver(new Handler()) {

					@Override
					public void onChange(boolean selfChange) {
						if (!mSmsCatching) {
							return;
						}
						Cursor cursor = DoctorDetailActivity.this
								.getContentResolver().query(
										Uri.parse("content://sms/outbox"),
										null, null, null, null);
						if (cursor.moveToFirst()) {
							String body = cursor.getString(cursor
									.getColumnIndex("body"));
							if (body.contains("皮肤科医生")) {
								mSmsCatching = false;
								doShareCallBack();
							}
						}
					}

				});
	}

	void registerReceiver() {
		IntentFilter filter = new IntentFilter(Constant.RECIVER_UPDATE_QUESTION);
		registerReceiver(questionReceiver, filter);
	}

	/**
	 * method desc：
	 */
	public void loadData(boolean isShowDialog) {
		params.put("startQid", start_qid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						list_question_detail.onPullDownRefreshComplete();
						list_question_detail.onPullUpRefreshComplete();
						list_question_detail.setLastUpdateTime();
						if (!CommonUtility.isNull(o)) {
							try {
								JSONObject object = (JSONObject) o;
								if (CommonUtility.response200(object)) {
									object = object.getJSONObject("Res");

									JSONArray arr = (JSONArray) object
											.getJSONArray("Questions");
									if (arr.length() > 0) {
										CommonUtility.putAll(array, arr, true);
										list_question_detail
												.setHasMoreData(true);
									} else {
										list_question_detail
												.setHasMoreData(false);
										list_question_detail.getLoadingLayout()
												.setHintText(null);
									}
									if (array.size() > 0) {
										start_qid = ((JSONObject) array
												.get(array.size() - 1))
												.getInt("Qid");
									} else {
										list_question_detail
												.getLoadingLayout()
												.setHintText(
														doctorInfo
																.getString("Name")
																+ "医生暂无解答记录，你来做第一个吧");
									}
									if (CommonUtility.isNull(adapter)) {
										adapter = new QuestionAdapter(activity,
												array);
										list_question_detail
												.setAdapter(adapter);
									} else {
										adapter.notifyUpdate();
									}
									if (array.size() < 1) {
										setContextEmptyType(true, 2);
									} else {
										setContextEmptyType(false, 2);
									}
								} else {
									setContextEmptyType(true, 2);
									CommonUtility.toast(activity,
											R.string.server_unavailable);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), isShowDialog, params);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		if (mLoadTreatment) {
			loadTreatment();
		} else {
			start_qid = 0;
			array.clear();
			loadData(false);
		}
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		if (mLoadTreatment) {
			loadTreatment();
		} else {
			loadData(false);
		}
	}

	private void loadTreatment() {
		DoctorTreatmentProjectListTask task = new DoctorTreatmentProjectListTask();

		DoctorTreatmentProjectListRequest req = new DoctorTreatmentProjectListRequest();
		req.doctorid = mUser.Uid;
		task.addListener(new NetTaskListener<DoctorTreatmentProjectListTask.DoctorTreatmentProjectListRequest, DoctorTreatmentProjectListTask.DoctorTreatmentProjectListResponse>() {

			@Override
			public void onComplete(
					INetTask<DoctorTreatmentProjectListRequest, DoctorTreatmentProjectListResponse> task,
					DoctorTreatmentProjectListResponse response) {
				list_question_detail.doComplete();
				if (response != null && response.size() > 0) {
					mAdapter.setDataProvider(response);
					setContextEmptyType(false, 2);
				} else {
					setContextEmptyType(true, 2);
					// list_question_detail.getLoadingLayout().setHintText(
					// mUser.Name + "医生还没有治疗项目");
				}
				mAdapter.notifyDataSetChanged();
			}

			@Override
			public void onException(
					INetTask<DoctorTreatmentProjectListRequest, DoctorTreatmentProjectListResponse> task,
					Exception e) {
				setContextEmptyType(true, 2);

				e.printStackTrace();
			}
		});
		task.setRequest(req);
		add(task);
	}

	private void setContextEmpty(boolean show, int drawableid, String text) {
		if (show) {
			mParent.setVisibility(View.VISIBLE);
			mTextEmpty.setCompoundDrawablesWithIntrinsicBounds(0, drawableid,
					0, 0);
			mTextEmpty.setText(text);
		} else {
			mParent.setVisibility(View.GONE);
		}
	}

	public void setContextEmptyType(boolean show, int type) {
		if (type == 1) {
			// 会话列表空
			setContextEmpty(show, R.drawable.session_empty, Constant.NOFRIEND);
		} else if (type == 2) {
			// 内容为空
			setContextEmpty(show, R.drawable.no_content, Constant.CONTENT_EMPTY);
		} else if (type == 3) {
			// 加载失败
			setContextEmpty(show, R.drawable.exception,
					Constant.CONTENT_EXCEPTION);
		}
	}

	int operate = 0;

	protected void showQuestionLimitDialog() {
		QuestionLimitDialog dialog = new QuestionLimitDialog(
				DoctorDetailActivity.this);
		dialog.setListener(new QuestionLimitDialogListener() {

			@Override
			public void onInviteWeixin() {
				String title = "皮肤科医生";
				String description = "还在为皮肤问题烦恼？大牌专家都在这里，去问问他们吧～";
				String url = "http://www.pifupro.com/download.html";
				ShareWXUtils.getInstance(DoctorDetailActivity.this)
						.share2WXWEB(url, title, description, false);
			}

			@Override
			public void onInviteQQ() {
				String title = "皮肤科医生";
				String description = "还在为皮肤问题烦恼？大牌专家都在这里，去问问他们吧～";
				String url = "http://www.pifupro.com/download.html";
				ShareQQUtils.getInstance(DoctorDetailActivity.this).share(url,
						title, description);
				doShareCallBack();
				ShareQQUtils.getInstance(DoctorDetailActivity.this)
						.setOnCompleteCallBack(new ShareCallBack() {

							@Override
							public void callback(Object obj) {
								doShareCallBack();
							}
						});

			}

			@Override
			public void onInviteContacts() {

				Intent intent = new Intent(Intent.ACTION_PICK,
						ContactsContract.Contacts.CONTENT_URI);
				try {
					startActivityForResult(intent,
							GlobalSettings.REQUEST_CODE_PICK_CONTACT);
				} catch (Exception e) {
				}

			}
		});
		dialog.show();
	}

	protected void doShareCallBack() {
		SysShareCallBackRequest req = new SysShareCallBackRequest();
		req.token = GlobalSettings.sToken;
		SysShareCallBackTask task = new SysShareCallBackTask();
		task.setRequest(req);
		add(task);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == GlobalSettings.REQUEST_CODE_PICK_CONTACT) {
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst()) {
					String name = c
							.getString(c
									.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String hasPhone = c.getString(c
							.getColumnIndex(Contacts.HAS_PHONE_NUMBER));
					if (!hasPhone.equals("1")) {
						return;
					}
					String contactId = c.getString(c
							.getColumnIndex(ContactsContract.Contacts._ID));
					Cursor pc = getContentResolver().query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = " + contactId, null, null);
					ArrayList<String> phones = new ArrayList<String>();
					if (pc.moveToNext()) {
						for (; !pc.isAfterLast(); pc.moveToNext()) {
							int index = pc
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
							String phone = pc.getString(index);
							phones.add(phone);
						}
					}
					if (!pc.isClosed()) {
						pc.close();
					}
					if (phones.size() == 0) {
						return;
					}
					ArrayList<ContactActionItem> actions = new ArrayList<QuestionFragment.ContactActionItem>();
					for (int i = 0; i < phones.size(); i++) {
						ContactActionItem item = new ContactActionItem();
						item.name = name;
						item.phone = phones.get(i);
						item.setText(item.phone);
						actions.add(item);
					}
					OActionSheet<ContactActionItem> actionSheet = new OActionSheet<ContactActionItem>(
							this);
					actionSheet.setCancel("取消");
					actionSheet.setDataProvider(actions);
					actionSheet
							.setOnActionItemClickListener(new OnActionItemClickListener<ContactActionItem>() {

								@Override
								public void onItemClick(
										OActionSheet<ContactActionItem> sheet,
										View v, int position,
										ContactActionItem dataItem) {
									final String smsPhoneNum = dataItem.phone;
									OAlert alert = new OAlert(
											DoctorDetailActivity.this);
									alert.setTitle(dataItem.name + ":"
											+ smsPhoneNum);
									alert.setCancel("取消");
									alert.setOK("发送");
									alert.setListener(new OAlertListener() {

										@Override
										public boolean onOK(OAlert alert) {
											String body = "皮肤科医生移动客户端，您的掌上皮肤专家。权威专家，在线解答。告别排队奔波，三甲医院带回家。点击链接立即下载：http://t.cn/RzdrWrM";

											Uri uri = Uri.parse("smsto:"
													+ smsPhoneNum);
											Intent intent = new Intent(
													Intent.ACTION_SENDTO, uri);
											intent.putExtra("sms_body", body);
											mSmsCatching = true;
											startActivity(intent);

											return false;
										}

										@Override
										public boolean onCancel(OAlert alert) {
											return false;
										}
									});
									alert.show();
								}
							});
					actionSheet.show(false, true);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		Intent intent = null;
		if (id == R.id.btn_guanzhu) {
			final TextView btn_guanzhu = (TextView) view;
			String text = btn_guanzhu.getText() + "";
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put(Constant.PARAM_API, "Follow.Set");
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			try {
				params.put("uids", doctor.getString("Uid"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if ("关注".equals(text)) {
				params.put("method", "add");
				operate = 1;
			} else if ("取消关注".equals(text)) {
				params.put("method", "cancle");
				operate = 0;
			}
			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST, new RequestHandler(activity,
							new HandlerCallback() {

								@Override
								public void callback(Object o) {
									if (!CommonUtility.isNull(o)) {
										JSONObject object = (JSONObject) o;
										if (CommonUtility.response200(object)) {
											if (operate == 0) {
												CommonUtility.toast(activity,
														"取消关注成功");
												btn_guanzhu.setText("关注");
												btn_guanzhu
														.setBackgroundResource(R.drawable.round_btn_green);
												int guanzhuNum = 0;
												// btn_guanzhu
												// .setTextColor(0xff36d49a);
												try {
													guanzhuNum = Integer
															.parseInt(text_guanzhu_num
																	.getText()
																	.toString()) - 1;
													text_guanzhu_num
															.setText(guanzhuNum
																	+ "");
												} catch (Exception e) {
													e.printStackTrace();
												}
											} else if (operate == 1) {
												CommonUtility.toast(activity,
														"关注成功");
												btn_guanzhu.setText("取消关注");
												btn_guanzhu
														.setTextColor(0xffffffff);
												int guanzhuNum = 0;
												try {
													guanzhuNum = Integer
															.parseInt(text_guanzhu_num
																	.getText()
																	.toString()) + 1;
													text_guanzhu_num
															.setText(guanzhuNum
																	+ "");
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
											// Intent data = new Intent(
											// Constant.RECIVER_QUESTION);
											// try {
											// data.putExtra(Constant.IDENTITY_KEY,
											// doctor.getInt("Uid"));
											// } catch (Exception e) {
											// e.printStackTrace();
											// }
											// data.putExtra(Constant.IDENTITY_KEY_1,
											// operate);
											// activity.sendBroadcast(data);
										} else {
											CommonUtility.toast(activity,
													"操作失败");
										}
									}
								}
							}), params);
		} else if (id == R.id.btn_charge_to_zixun) {
			if (GlobalSettings.sToken == null) {

				Log.i("testtoken", "DoctorDetailActivity");

				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			try {
				double cost = doctorInfo.getDouble("Cost");
				/*
				 * if (cost > 0) { intent = new Intent(activity,
				 * Cost2DoctorActivity.class);
				 * intent.putExtra(Constant.IDENTITY_KEY,
				 * doctorInfo.toString()); startActivity(intent); } else {
				 */
				QuestionLimitCheckRequest req = new QuestionLimitCheckRequest();
				req.token = GlobalSettings.sToken;
				QuestionLimitCheckTask task = new QuestionLimitCheckTask();
				task.setRequest(req);
				task.addListener(new NetTaskListener<QuestionLimitCheckTask.QuestionLimitCheckRequest, QuestionLimitCheckTask.QuestionLimitCheckResponse>() {

					@Override
					public void onException(
							INetTask<QuestionLimitCheckRequest, QuestionLimitCheckResponse> task,
							Exception e) {

					}

					@Override
					public void onComplete(
							INetTask<QuestionLimitCheckRequest, QuestionLimitCheckResponse> task,
							QuestionLimitCheckResponse response) {
						if (response.ResultCode != 200) {
							return;
						}
						if (response.Res.IsLimited == GlobalSettings.IS_TRUE) {
							showQuestionLimitDialog();
						} else {
							Intent intent = new Intent(activity,
									CreateQuestionActivity.class);
							intent.putExtra(Constant.IDENTITY_KEY_DOCTOR_INFO,
									doctorInfo.toString());
							intent.putExtra(
									Constant.IDENTITY_KEY_CREATE_COST_2_DOCTOR,
									true);
							intent.putExtra(
									Constant.IDENTITY_KEY_QUESTION_EDIT, true);
							startActivity(intent);
						}
					}
				});
				add(task);
				// }
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (id == R.id.btn_charge_to_zixun_by_invite) {
			intent = new Intent(activity, InviteZixunActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, doctorInfo.toString());
			startActivity(intent);
		} else if (id == R.id.rl_comment) {
			intent = new Intent(activity, CommentActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, doctorInfo.toString());
			startActivity(intent);
		} else if (id == R.id.ll_answer) {
			intent = new Intent(activity, DoctorAnswerActivity.class);
			// 标识由其他医生或者患者在医生详情点击
			intent.putExtra(Constant.IDENTITY_KEY_1, true);
			intent.putExtra(Constant.IDENTITY_KEY, doctorInfo.toString());
			startActivity(intent);
		} else if (id == R.id.ll_comment) {
			intent = new Intent(activity, CommentActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, doctorInfo.toString());
			intent.putExtra(Constant.IDENTITY_KEY_1, 3);
			startActivity(intent);
		} else if (id == R.id.ll_guanzhu) {
			intent = new Intent(activity, OtherDoctorGuanzhuActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, doctorInfo.toString());
			startActivity(intent);
		} else if (id == R.id.text_right) {
			if (!CommonUtility.isNull(GlobalSettings.sUser)) {
				try {
					String url = GlobalSettings.SERVER_URL_TREATMENT
							+ "WeChat/MenuData/doctorHome/doctorid/"
							+ doctorInfo.getString("Uid");
					StringBuilder title = new StringBuilder();
					title.append(doctorInfo.getString("Name"))
							.append("(")
							.append(CommonUtility.convertJSONArray2String(
									doctorInfo.getJSONArray("Professional"),
									",")).append(")");
					StringBuilder description = new StringBuilder();
					description
							.append(doctorInfo.getString("Hospital"))
							.append(",")
							.append("擅长：")
							.append(CommonUtility.convertJSONArray2String(
									doctorInfo.getJSONArray("Skilled"), "，"));
					ShareUtil.share(this, url, title, description);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				activity.startActivity(new Intent(activity, LoginActivity.class));
			}
		}
	}

	protected void onDestroy() {
		super.onDestroy();
		if (!CommonUtility.isNull(questionReceiver)) {
			unregisterReceiver(questionReceiver);
		}
	}

	BroadcastReceiver questionReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			list_question_detail.doPullRefreshing(true);
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (mLoadTreatment) {
			if (position != 0) {
				DoctorTreatmentProjectItem item = (DoctorTreatmentProjectItem) mAdapter
						.getDataProvider().get((int) id);
				Intent i = new Intent(getContext(),
						TreatmentDetailActivity.class);
				TreatmentProjectItemExtra extra = new TreatmentProjectItemExtra();
				extra.setUser(item);
				if (extra.putTo(i)) {
					startActivity(i);
				}
			}
		} else {
			Intent intent = new Intent(activity, QuestionDetailActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, array.get((int) id)
					.toString());
			activity.startActivity(intent);
		}
	}

	/*
	 * @Override public void onResume() { super.onResume();
	 * MobclickAgent.onResume(getContext()); }
	 * 
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
